import React, {useState} from 'react'

interface AppStateValue {
  userType: string;
  shoppingCart: {items: {id: number, name: string}[]}
} 

const defaultContextValue : AppStateValue = {
  userType: '超级会员',
  shoppingCart: {
    items: []
  }
}
export const appContext = React.createContext(defaultContextValue)
export const appSetStateContext = React.createContext<React.Dispatch<React.SetStateAction<AppStateValue>> | undefined>(undefined)

// 相当于高阶函数(HOC),把所有子组件全部包裹起来,并从全局的角度提供数据的支持,所以会return一个包裹子组件的Provider
export const AppStateProvider: React.FC = (props) => {
  const [state, setState] = useState(defaultContextValue)
  return (
    <appContext.Provider value={state}>
      <appSetStateContext.Provider value={setState}>
        {props.children}
      </appSetStateContext.Provider>
    </appContext.Provider>
  ) 
}